import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:speed_random/core/http/api_ad.dart';
import 'package:speed_random/core/http/ws_app_test.dart';
import 'package:speed_random/global_data.dart';
import '../../core/services/ad_service.dart';

class GoogleAdService implements AdService {
  @override
  bool get allNotShow => false; // 根据实际VIP状态返回

  @override
  Future<void> initialize() async {
    await MobileAds.instance.initialize();
  }



@override
Future<void> getBannerAd(Function(Widget) onAdLoaded) async {
   await AdManager().loadBannerAd(
    size: AdSize.banner,
    onAdLoaded: (ad) {
      onAdLoaded(
        Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(vertical: 10),
          child: SizedBox(
            width: 320,
            height: 50,
            child: AdWidget(ad: ad as BannerAd), // 添加类型转换
          ),
        ),
      );
    },
    onAdFailedToLoad: (ad, error) {
      ad.dispose();
      if (kDebugMode) {
        wsPrint('Banner广告加载失败: $error');
      }
    },
  );
}


  @override
  Future<void> showRewardedAd() async {
    await AdManager().loadRewardedAd(
      onAdLoaded: (ad) {
        AdManager().showRewardedAd(
          onUserEarnedReward: (ad, reward) {
            wsPrint('用户获得奖励: ${reward.amount} ${reward.type}');
          },
          onAdDismissed: (_) => wsPrint('激励广告已关闭'),
        );
      },
      onAdFailedToLoad: (error) => wsPrint('激励广告加载失败: $error'), onUserEarnedReward: (RewardedAd , RewardItem ) {  },
    );
  }

  @override
  Future<void> showInterstitialAd() async {
    await AdManager().loadInterstitialAd(
      onAdLoaded: (ad) {
        AdManager().showInterstitialAd(
          onAdShowed: (_) => wsPrint('插页广告已展示'),
          onAdDismissed: (_) => wsPrint('插页广告已关闭'),
        );
      },
      onAdFailedToLoad: (error) => wsPrint('插页广告加载失败: $error'),
    );
  }

  @override
  Future<void> showAppOpenAd() async {
    await AdManager().loadAppOpenAd(
      onAdLoaded: (ad) {
        AdManager().showAppOpenAd(
          onAdShowed: (_) => wsPrint('开屏广告已展示'),
          onAdDismissed: (_) => wsPrint('开屏广告已关闭'),
        );
      },
      onAdFailedToLoad: (error) => wsPrint('开屏广告加载失败: $error'),
    );
  }

  @override
  Future<void> showNativeAdvancedAd(Function(Widget) onAdLoaded) async {
    await AdManager().loadNativeAdvancedAd(
      onAdLoaded: (ad) {
        final adWidget = AdWidget(ad: ad);
        AdManager().showNativeAdvancedAd(
          onAdShowed: (_) {
            wsPrint('原生广告已展示');
            onAdLoaded(Container(
              height: 200, // 设置广告容器高度
              margin: EdgeInsets.only(bottom: 10),
              child: adWidget,
            ));
          },
          onAdDismissed: (_) => wsPrint('原生广告已关闭'),
        );
      },
      onAdFailedToLoad: (error) => wsPrint('原生广告加载失败: $error'),
    );
  }

  @override
  Future<void> showRewardedInterstitialAd() async {
    await AdManager().loadRewardedInterstitialAd(
      onAdLoaded: (ad) {
        AdManager().showRewardedInterstitialAd(
          onUserEarnedReward: (ad, reward) {
            wsPrint('用户获得奖励: ${reward.amount} ${reward.type}');
          },
          onAdDismissed: (_) => wsPrint('插页激励广告已关闭'),
        );
      },
      onAdFailedToLoad: (error) => wsPrint('插页激励广告加载失败: $error'), onUserEarnedReward: (RewardedInterstitialAd , RewardItem ) {  },
    );
  }

  @override
  Future<void> showAd({
    required AdType adType,
    Function()? callback,
    Function(Widget)? onAdLoadedBanner,
    bool forceShow = false,
  }) async {
    if (globalData.userInfo.isvip==true) {
      wsPrint("VIP用户，不展示广告: ${adType.name}");
      return;
    }
    wsPrint("-------广告: ${adType.name}");

    if (!forceShow) {
      var show = await ApiAd.showAd(adType);
      if (!show) {
        return;
      }
    }

    try {
      switch (adType) {
        case AdType.banner:
          await getBannerAd((widget) {
            onAdLoadedBanner?.call(widget);
            callback?.call();
          });
          break;
        case AdType.rewarded:
          await showRewardedAd();
          break;
        case AdType.interstitial:
          await showInterstitialAd();
          break;
        case AdType.appOpen:
          await showAppOpenAd();
          break;
        case AdType.rewardedInterstitial:
          await showRewardedInterstitialAd();
          break;
        case AdType.nativeAdvanced:
          await showNativeAdvancedAd((widget) {
            onAdLoadedBanner?.call(widget);
            callback?.call();
          });
          break;
      }
      callback?.call();
    } catch (e) {
      wsPrint('广告展示异常: $e');
    }
  }

}

/// 广告管理类（单例模式）
class AdManager {
  // 单例实例
  static final AdManager _instance = AdManager._internal();
  factory AdManager() => _instance;

  AdManager._internal();
  /// 获取当前加载的原生广告
  NativeAd? get nativeAd => _nativeAd;
  // 测试广告单元 ID
  static const _testAdUnitIds = {
    AdType.banner: 'ca-app-pub-3940256099942544/6300978111',
    AdType.interstitial: 'ca-app-pub-3940256099942544/1033173712',
    AdType.rewardedInterstitial: 'ca-app-pub-3940256099942544/5354046379',
    AdType.rewarded: 'ca-app-pub-3940256099942544/5224354917',
    AdType.nativeAdvanced: 'ca-app-pub-3940256099942544/2247696110',
    AdType.appOpen: 'ca-app-pub-3940256099942544/3419835294',
  };

  // 应用程序名称：SpeedRandom 真实Google 安卓版 广告ID     ca-app-pub-9033884045199794~5670364074
  static const _prodAdUnitIds = {
    AdType.banner: 'ca-app-pub-9033884045199794/9194676112', //banner广告 横幅广告
    AdType.interstitial: 'ca-app-pub-9033884045199794/5471053529',// 插页广告
    AdType.rewardedInterstitial: 'ca-app-pub-9033884045199794/4929780431',//插页式激励广告
    AdType.rewarded: 'ca-app-pub-9033884045199794/3672539080',// 激励广告
    AdType.nativeAdvanced: 'ca-app-pub-9033884045199794/2359457417',//原生广告
    AdType.appOpen: 'ca-app-pub-9033884045199794/4976245411',// 开屏广告
  };

  /// 当前广告实例
  BannerAd? _bannerAd;
  InterstitialAd? _interstitialAd;
  RewardedInterstitialAd? _rewardedInterstitialAd;
  RewardedAd? _rewardedAd;
  NativeAd? _nativeAd;
  AppOpenAd? _appOpenAd;

  /// 初始化 AdMob
  Future<void> initialize() async {
    await MobileAds.instance.initialize();
    if (kDebugMode) {
      // 调试模式下设置测试设备
      MobileAds.instance.updateRequestConfiguration(
        RequestConfiguration(
          testDeviceIds: ['YOUR_TEST_DEVICE_HASH'], // 替换为你的测试设备ID
        ),
      );
    }
  }

  /// 获取广告单元ID（自动区分环境）
  String _getAdUnitId(AdType type) {
    final adUnitId = kReleaseMode ? _prodAdUnitIds[type]! : _testAdUnitIds[type]!;
    if (kDebugMode) {
      wsPrint('当前广告类型: $type, 广告单元 ID: $adUnitId');
    }
    return adUnitId;
  }

  /// 加载横幅广告
  Future<BannerAd> loadBannerAd({
    required AdSize size,
    required void Function(Ad) onAdLoaded,
    required void Function(Ad, LoadAdError) onAdFailedToLoad,
  }) async {
    _bannerAd?.dispose();

    _bannerAd = BannerAd(
      adUnitId: _getAdUnitId(AdType.banner),
      request: const AdRequest(),
      size: size,
      listener: BannerAdListener(
        onAdLoaded: onAdLoaded,
        onAdFailedToLoad: (ad, error) {
          ad.dispose();
          onAdFailedToLoad(ad, error);
        },
      ),
    )..load();

    return _bannerAd!;
  }

  /// 加载插页广告
  Future<void> loadInterstitialAd({
    required void Function(InterstitialAd) onAdLoaded,
    required void Function(LoadAdError) onAdFailedToLoad,
  }) async {
    await InterstitialAd.load(
      adUnitId: _getAdUnitId(AdType.interstitial),
      request: const AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (ad) {
          _interstitialAd = ad;
          onAdLoaded(ad);
        },
        onAdFailedToLoad: (error) {
          _interstitialAd = null;
          onAdFailedToLoad(error);
        },
      ),
    );
  }

  /// 显示插页广告
  void showInterstitialAd({
    void Function(InterstitialAd)? onAdShowed,
    void Function(InterstitialAd)? onAdDismissed,
    void Function(InterstitialAd, AdError)? onAdFailedToShow,
  }) {
    if (_interstitialAd != null) {
      _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
        onAdShowedFullScreenContent: (ad) => onAdShowed?.call(ad),
        onAdDismissedFullScreenContent: (ad) {
          ad.dispose();
          _interstitialAd = null;
          onAdDismissed?.call(ad);
        },
        onAdFailedToShowFullScreenContent: (ad, error) {
          ad.dispose();
          _interstitialAd = null;
          onAdFailedToShow?.call(ad, error);
        },
      );
      _interstitialAd!.show();
    }
  }

  /// 加载激励插页广告
  Future<void> loadRewardedInterstitialAd({
    required void Function(RewardedInterstitialAd) onAdLoaded,
    required void Function(LoadAdError) onAdFailedToLoad,
    required void Function(RewardedInterstitialAd, RewardItem) onUserEarnedReward,
  }) async {
    await RewardedInterstitialAd.load(
      adUnitId: _getAdUnitId(AdType.rewardedInterstitial),
      request: const AdRequest(),
      rewardedInterstitialAdLoadCallback: RewardedInterstitialAdLoadCallback(
        onAdLoaded: (ad) {
          _rewardedInterstitialAd = ad;
          onAdLoaded(ad);
        },
        onAdFailedToLoad: (error) {
          _rewardedInterstitialAd = null;
          onAdFailedToLoad(error);
        },
      ),
    );
  }
  /// 显示原生高级广告
  void showNativeAdvancedAd({
    required void Function(NativeAd) onAdShowed,
    void Function(NativeAd)? onAdDismissed,
  }) {
    if (_nativeAd != null) {
      onAdShowed(_nativeAd!);
      // 原生广告通常不需要关闭回调，这里只是保持接口一致
    }
  }
  /// 显示激励插页广告
  void showRewardedInterstitialAd({
    required void Function(RewardedInterstitialAd, RewardItem) onUserEarnedReward,
    void Function(RewardedInterstitialAd)? onAdDismissed,
  }) {
    if (_rewardedInterstitialAd != null) {
      _rewardedInterstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
        onAdDismissedFullScreenContent: (ad) {
          ad.dispose();
          _rewardedInterstitialAd = null;
          onAdDismissed?.call(ad as RewardedInterstitialAd);
        },
      );
      _rewardedInterstitialAd!.show(
        onUserEarnedReward: (ad, reward) => onUserEarnedReward(ad as RewardedInterstitialAd, reward),
      );
    }
  }

  /// 加载激励广告
  Future<void> loadRewardedAd({
    required void Function(RewardedAd) onAdLoaded,
    required void Function(LoadAdError) onAdFailedToLoad,
    required void Function(RewardedAd, RewardItem) onUserEarnedReward,
  }) async {
    await RewardedAd.load(
      adUnitId: _getAdUnitId(AdType.rewarded),
      request: const AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(
        onAdLoaded: (ad) {
          _rewardedAd = ad;
          onAdLoaded(ad);
        },
        onAdFailedToLoad: (error) {
          _rewardedAd = null;
          onAdFailedToLoad(error);
        },
      ),
    );
  }

  /// 显示激励广告
  void showRewardedAd({
    required void Function(RewardedAd, RewardItem) onUserEarnedReward,
    void Function(RewardedAd)? onAdDismissed,
  }) {
    if (_rewardedAd != null) {
      _rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
        onAdDismissedFullScreenContent: (ad) {
          ad.dispose();
          _rewardedAd = null;
          onAdDismissed?.call(ad as RewardedAd);
        },
      );
      _rewardedAd!.show(
        onUserEarnedReward: (ad, reward) => onUserEarnedReward(ad as RewardedAd, reward),
      );
    }
  }
  /// 加载原生高级广告
  Future<NativeAd> loadNativeAdvancedAd({
    required void Function(NativeAd) onAdLoaded,
    required void Function(LoadAdError) onAdFailedToLoad,
  }) async {
    final ad = NativeAd(
      adUnitId: _getAdUnitId(AdType.nativeAdvanced),
      request: const AdRequest(),
      listener: NativeAdListener(
        onAdLoaded: (ad) {
          _nativeAd = ad as NativeAd;
          onAdLoaded(_nativeAd!);
        },
        onAdFailedToLoad: (ad, error) {
          ad.dispose();
          onAdFailedToLoad(error);
        },
      ),
      nativeTemplateStyle: NativeTemplateStyle(
        templateType: TemplateType.medium,
        mainBackgroundColor: const Color.fromARGB(255, 255, 255, 255),
        cornerRadius: 16.0,
        callToActionTextStyle: NativeTemplateTextStyle(
          size: 16.0,
          textColor: const Color.fromARGB(255, 255, 255, 255),
          backgroundColor: const Color.fromARGB(255, 0, 128, 255),
        ),
        primaryTextStyle: NativeTemplateTextStyle(
          size: 16.0,
          textColor: const Color.fromARGB(255, 0, 0, 0),
        ),
        secondaryTextStyle: NativeTemplateTextStyle(
          size: 12.0,
          textColor: const Color.fromARGB(255, 128, 128, 128),
        ),
        tertiaryTextStyle: NativeTemplateTextStyle(
          size: 12.0,
          textColor: const Color.fromARGB(255, 128, 128, 128),
        ),
      ),
    );
    await ad.load();
    return ad;
  }
  /// 加载原生高级广告
  Future<NativeAd> loadNativeAdvancedAd_bak({
    required void Function(NativeAd) onAdLoaded,
    required void Function(LoadAdError) onAdFailedToLoad,
  }) async {
    final ad = NativeAd(
      adUnitId: _getAdUnitId(AdType.nativeAdvanced),
      factoryId: 'adFactoryExample',
      request: const AdRequest(),
      listener: NativeAdListener(
        onAdLoaded: (ad) {
          if (ad is NativeAd) {
            _nativeAd = ad;
            onAdLoaded(_nativeAd!);
          } else {
            if (kDebugMode) {
              wsPrint('加载的广告不是 NativeAd 类型');
            }
            ad.dispose();
            // onAdFailedToLoad(LoadAdError(0, 'Unexpected ad type', 'NativeAd', ""));
          }
        },
        onAdFailedToLoad: (ad, error) {
          if (kDebugMode) {
            wsPrint('原生高级广告加载失败: $error');
          }
          ad.dispose();
          onAdFailedToLoad(error);
        },
      ),
    );
    return ad..load();
  }

  /// 加载开屏广告
  Future<void> loadAppOpenAd({
    required void Function(AppOpenAd) onAdLoaded,
    required void Function(LoadAdError) onAdFailedToLoad,
  }) async {
    await AppOpenAd.load(
      adUnitId: _getAdUnitId(AdType.appOpen),
      request: const AdRequest(),
      adLoadCallback: AppOpenAdLoadCallback(
        onAdLoaded: (ad) {
          _appOpenAd = ad;
          onAdLoaded(ad);
        },
        onAdFailedToLoad: (error) {
          _appOpenAd = null;
          onAdFailedToLoad(error);
        },
      ),
    );
  }

  /// 显示开屏广告
  void showAppOpenAd({
    void Function(AppOpenAd)? onAdShowed,
    void Function(AppOpenAd)? onAdDismissed,
    void Function(AppOpenAd, AdError)? onAdFailedToShow,
  }) {
    if (_appOpenAd != null) {
      _appOpenAd!.fullScreenContentCallback = FullScreenContentCallback(
        onAdShowedFullScreenContent: (ad) => onAdShowed?.call(ad),
        onAdDismissedFullScreenContent: (ad) {
          ad.dispose();
          _appOpenAd = null;
          onAdDismissed?.call(ad);
        },
        onAdFailedToShowFullScreenContent: (ad, error) {
          ad.dispose();
          _appOpenAd = null;
          onAdFailedToShow?.call(ad, error);
        },
      );
      _appOpenAd!.show();
    }
  }

  /// 释放所有广告资源
  void dispose() {
    _bannerAd?.dispose();
    _interstitialAd?.dispose();
    _rewardedInterstitialAd?.dispose();
    _rewardedAd?.dispose();
    _nativeAd?.dispose();
    _appOpenAd?.dispose();
  }
}